package com.training.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

//CacheProperties本身是没有注入spring容器的，为了能取到
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
//单纯的开启缓存把这个注解写在启动类上就行了
@EnableCaching
public class MyCacheConfig {

//    @Autowired
//    CacheProperties cacheProperties;

    /**
     * 使用自己的RedisCacheConfiguration，application.yml中的配置就不会应用上了
     * 原始详见org.springframework.boot.autoconfigure.cache的80行
     * 其中使其取值生效的写法：
     *      @ConfigurationProperties(prefix = "spring.cache")
     *      public class CacheProperties
     * 我使用注解 @EnableConfigurationProperties(CacheProperties.class)
     * 在形参上传入CacheProperties cacheProperties，它会自动找spring容器要这个对象
     * 也可以写个成员属性@Autowrite
     * @return
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //使存入redis中的 k-v 按我们指定的格式存入，默认的方式，Value会是jdk的序列化机制，Value根本没有可读性，这里使用的是阿里巴巴的通用型fastjson，也可以用org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;spring自带的通用json
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //自己手动让application.yml中的配置生效
        //与源码一致，详细作用见源码
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}

